<template>
  <div class="content">
    <div class="titleBox" v-if="flag === false">
      <div class="title"
        :style="week === true ? 'background-color:rgb(236, 65, 65);color:#fff' : 'background-color:#fff'"
        @click="change()">最近一周</div>
      <div class="title"
        :style="week === false ? 'background-color:rgb(236, 65, 65);color:#fff' : 'background-color:#fff'"
        @click="change()">所有时间</div>
    </div>

    <el-table :data="data" stripe style="width: 100%" size="medium" @row-dblclick="play"
      :row-class-name="tableRowClassName" :row-style="selectedstyle" @row-contextmenu="rightList">
      <el-table-column type="index"></el-table-column>
      <el-table-column width="40">
        <div class="el-icon-video-play"></div>
      </el-table-column>

      <el-table-column prop="name" label="音乐标题">
        <template slot-scope="scope">
          <div class="musicTitle">
            <div class="rowName">
              {{ flag === true ? scope.row.name : scope.row.song.name }}
            </div>
            <div
              v-if="flag === true ? scope.row.fee === 1 && scope.row.fee === 8 : scope.row.song.fee === 1 && scope.row.song.fee === 8"
              class="vip">
              VIP
            </div>
            <div>
              <el-image :src="require('../assets/image/SQ.jpg')"
                v-if="flag === true ? scope.row.fee === 8 : scope.row.song.fee === 8"></el-image>
            </div>
            <div v-if="flag === true ? scope.row.originCoverType === 2 : scope.row.song.originCoverType === 2"
              class="oringin">
              翻唱
            </div>
            <div v-if="flag === true ? scope.row.mv !== 0 : scope.row.song.mv !== 0" class="mv"
              @click="playMv(flag === true ? scope.row : scope.row.song)">
              MV
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="ar.name" label="歌手">
        <template slot-scope="scope">
          <div class="nameBox">
            <div v-for="(item, i) in  flag === true ? scope.row.ar : scope.row.song.ar" :key="i">
              <el-tooltip class="item" effect="dark"
                :content="flag === true ? scope.row.ar[i].name : scope.row.song.ar[i].name" placement="top">
                <div @click="getArt(flag === true ? scope.row.ar[i].name : scope.row.song.ar[i].name)" class="art">
                  {{ flag === true ? scope.row.ar[i].name : scope.row.song.ar[i].name }}
                </div>
              </el-tooltip>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="专辑" :filters="filters" :filter-method="filterHandler">
        <template slot-scope="scope">
          <div @click="getAlb(flag === true ? scope.row.al : scope.row.song.al)" class="art"
            v-if="flag === true ? scope.row.al !== null : scope.row.song.al !== null" style="width: 120px;">
            {{ flag === true ? scope.row.al.name : scope.row.song.al.name }}
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="dt" label="时长">
        <template slot-scope="scope">
          {{ Math.floor(flag === true ? scope.row.dt / 1000 : scope.row.song.dt / 1000) | timeFormat }}
        </template>
      </el-table-column>

      <el-table-column label="播放次数" v-if="flag === false">
        <template slot-scope="scope">
          <div>
            {{ scope.row.playCount === 0 ? '无' : scope.row.playCount }}
          </div>
        </template>
      </el-table-column>
    </el-table>


    <div class="loading" v-if="show === true">
      <i class="el-icon-loading"></i>
    </div>
    <Memu />
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  components: {
    Memu: () => import('../components/rightMemu.vue'),
  },
  computed: {
    ...mapState(['nowPlaySong', 'preSong', 'nowPlaySong', 'userid']), // 读取VUEX中的状态
  },
  props: [
    'songData',
    'flag'

  ],
  mounted() {
    if (this.songData !== null) {
      this.data = this.songData
    }
    if (this.nowPlaySong !== null) {
      this.songId = this.nowPlaySong.songId
    }
    if (this.userid !== null) {
      this.uid = this.userid.userid
    }
    this.unique()
  },


  watch: {
    songData(newVal, oldVal) {
      this.data = newVal
      this.unique()
    },
    nowPlaySong(newVal, oldVal) {
      this.songId = newVal.songId;
    },
  },
  data() {
    return {
      data: [],
      show: false,
      songId: '',
      getIndex: '',
      filters: [],
      arr: '',
      week: true,
      uid: ''
    }
  },
  beforeRouteLeave(to, from, next) {
    this.data = []
    next()
  },
  methods: {
    ...mapActions([
      'saveNowSong',
      'saveSongList',
      'saveAlbumData',
      'clickPlay',
      'saveNowId',
      'saveNowSongCount',
      'saveMVurl',
      'saveResMv',
      'saveMvBes',
      'saveArtistsItem',
      'saveNowRow',
    ]),

    unique() {
      this.filters = []
      if (this.flag === true) {
        for (let i = 0; i < this.data.length; i++) {
          if (this.data[i].al === null) {
            continue
          } else {
            this.filters.push({ text: this.data[i].al.name, value: this.data[i].al.name })
          }
        }
      } else {
        for (let i = 0; i < this.data.length; i++) {
          if (this.data[i].song.al === null) {
            continue
          } else {
            this.filters.push({ text: this.data[i].song.al.name, value: this.data[i].song.al.name })
          }
        }
      }
      const hash = {};
      this.filters = this.filters.reduce((preVal, curVal) => {
        hash[curVal.text] ? '' : hash[curVal.text] = true && preVal.push(curVal);
        return preVal
      }, [])
    },

    async play(row) {
      const e = localStorage.getItem('cookie');
      const title = this.flag === true ? row.name : row.song.name;
      if (this.flag === true ? row.ar !== null : row.song.ar !== null) {
        if (this.flag === true) {
          this.arr = row.ar.map((item) => {
            return item.name;
          });
        } else {
          this.arr = row.song.ar.map((item) => {
            return item.name;
          });
        }

      }
      const artist = this.arr.join();
      const pic = this.flag === true ? row.al.picUrl : row.song.al.picUrl;
      this.songId = this.flag === true ? row.id : row.song.id;
      this.getIndex = row.row_index;
      this.$api.songUrl({ cookie: e, id: this.songId }).then((ret) => {
        this.songId = this.flag === true ? row.id : row.song.id;
        if (ret.data[0].url !== null) {
          this.saveNowSong({
            id: this.getIndex,
            title,
            artist,
            src: ret.data[0].url,
            pic,
            songId: this.songId,
          });
          this.clickPlay({ ifPlay: false });
          if (this.flag === true) {
            this.saveNowSongCount({ nowSongCount: this.data });
            this.$api.scrobble({ id: this.songId, cookie: e, sourceid: row.al.id, timestamp: this.$utils.timestamp() })
          } else {
            let data = []
            this.data.map((item) => {
              data.push(item.song)
            })
            this.saveNowSongCount({ nowSongCount: data })
            this.$api.scrobble({ id: this.songId, cookie: e, sourceid: row.song.al.id, timestamp: this.$utils.timestamp() })
          }
        } else {
          this.$message.error('该歌曲暂时无法播放!!!');
        }
      });
    },

    tableRowClassName({ row, rowIndex }) {
      row.row_index = rowIndex;
    },

    // 设置行的颜色
    selectedstyle({ row, rowIndex }) {
      if (this.songId === (this.flag === true ? row.id : row.song.id)) {
        return {
          color: '#ec4141',
        };
      }
    },

    // 右键菜单
    rightList(row, column, event) {
      window.sessionStorage.setItem('getIndex', this.getIndex);
      this.saveNowRow({ nowRow: this.flag === true ? row : row.song })
      document.querySelector('.list').style.left = `${event.clientX}px`
      document.querySelector('.list').style.top = `${event.pageY}px`
      const top = parseInt(document.querySelector('.list').style.top)
      const height = document.querySelector('.list').offsetHeight
      if (top + height >= event.screenY) {
        document.querySelector('.list').style.top = `${event.screenY - height - 60}px`
      }
    },

    // 跳转到歌手页面
    getArt(e) {
      this.show = true;
      window.sessionStorage.setItem('artists', e);
      this.$router.push(`/artistsPage?id=${e}`);
    },

    // 跳转到专辑页面
    async getAlb(e) {
      this.show = true;
      this.$api.album({ id: e.id, cookie: localStorage.getItem('cookie') }).then((ret) => {
        window.sessionStorage.setItem('album', e.id);
        this.saveAlbumData({ albumData: ret });
        this.$router.push(`/albumPage?id=${e.id}`);
      });
    },

    // 点击播放MV
    playMv(e) {
      // 获取到MV的地址
      this.$api.mvUrl({ id: parseInt(e.mv), cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveMVurl({ mvUrl: ret.data.url });
      });
      this.getArtists(e.ar[0].id);
      this.getResMv(e.mv);
      this.getItem(e.mv);
    },

    // 获取相似MV
    async getResMv(e) {
      this.$api.simiMv({ mvid: e, cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveResMv({ resMv: ret });
      });
    },

    // 获取MV基础信息
    async getItem(e) {
      this.loading = true;
      this.$api.mvDetail({ mvid: e, cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveMvBes({ mvBes: ret });
        this.$router.push(`/mvPlay?id=${e}`);
      });
    },

    // 获取MV作者
    async getArtists(e) {
      window.sessionStorage.setItem('artists', e);
      this.$api.arDetail({ id: e, cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveArtistsItem({ artistsItem: ret.data });
      });
    },


    filterHandler(value, row, column) {
      if (row.al !== null) {
        return row.al.name === value;
      }
    },

    change() {
      if (this.week === true) {
        this.week = false
        this.getData(0)
      } else {
        this.week = true
        this.getData(1)
      }
    },

    getData(e) {
      this.data = null
      this.show = true
      this.$api.recentSong({ uid: this.uid, type: e, cookie: localStorage.getItem('cookie'), timestamp: this.$utils.timestamp() }).then((ret) => {
        if (this.week === false) {
          this.data = ret.allData
        } else {
          this.data = ret.weekData
        }
      })
      this.show = false
    }
  },
}
</script>

<style scoped>
.content {
  margin-bottom: 40px;
}

.more {
  cursor: pointer;
}

.nameBox {
  display: flex;
}

.art {
  cursor: pointer;
  width: 60px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.loading {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
}

.rowName {
  width: 150px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-icon-loading {
  position: fixed;
  font-size: 50px;
  left: 50%;
  top: 50%;
  color: #ec4141;
}

.musicTitle {
  display: flex;
  align-items: center;
}

.el-image {
  display: flex;
  align-items: center;
  margin-right: 8px;
}

.vip {
  width: 27px;
  height: 15px;
  border: 1px solid orangered;
  font-size: 10px;
  color: orangered;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  margin-right: 8px;
}

.oringin {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 15px;
  border: 1px solid rgb(90, 86, 86);
  color: rgb(87, 75, 75);
  border-radius: 2px;
  font-size: 10px;
  margin-right: 8px;
}

.mv {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 27px;
  height: 15px;
  border: 1px solid #ec4141;
  color: #ec4141;
  border-radius: 2px;
  font-size: 10px;
}

.titleBox {
  display: flex;
  justify-content: right;
  margin-top: 10px;
  align-items: center;
}


.title {
  padding: 5px 10px;
  font-size: 15px;
  border-radius: 15px;
  cursor: pointer;
  margin-right: 10px;
}
</style>
